#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/8/15 17:21
# @Author  : youfeng
import random
import time

import requests

from enum.proxy_key import ProxyKey
from ext.proxy_base import ProxyBase

# 标注类名
__CLASS__ = "ProxyQuanwang"
# 标注是否使用当前代理
__USED__ = False


class ProxyQuanwang(ProxyBase):
    # 代理唯一标识
    __TAG__ = "quanwang"

    __QUANWANGPROXY_API = 'http://dynamic.goubanjia.com/dynamic/get/aa0c97be8d3685a49a30d9940f6de998.html?sep=3&ttl=1&random=true'

    def __init__(self, log):
        super(ProxyQuanwang, self).__int__(log=log)

    def get_proxy_tag(self):
        return self.__TAG__

    # 解析全网代理
    def __parse_quanwang_proxy(self, line_info):
        try:
            proxy = line_info.split(",")[0]
            live_time = int(line_info.split(",")[1])

            return proxy, int(time.time()) + (live_time / 1000)
        except Exception as e:
            self.log.error("解析全网代理异常:")
            self.log.exception(e)

        return None, None

    # 返回代理
    def get_proxy_list(self):

        for _ in xrange(3):
            proxy_list = []
            proxy_set = set()
            try:
                r = requests.get(self.__QUANWANGPROXY_API, timeout=10)
                if r is None or r.status_code != 200:
                    self.log.error("更新全网代理网络异常...")
                    time.sleep(random.randint(1, 3))
                    continue

                if "{" in r.text or "}" in r.text:
                    self.log.error("全网代理更新异常: text = {}".format(r.text))
                    time.sleep(random.randint(1, 2))
                    continue

                line_list = r.text.strip().split('\n')
                for line in line_list:
                    line = line.strip().strip("\r").strip("\n")
                    if len(line) <= 0:
                        continue

                    ip, expire_time = self.__parse_quanwang_proxy(line)
                    if ip is None:
                        continue

                    if ip in proxy_set:
                        continue

                    proxy_set.add(ip)

                    proxy = 'http://{}'.format(ip)
                    proxy_list.append({
                        ProxyKey.EXPIRE_TIME_KEY: expire_time,
                        ProxyKey.PROXY_KEY: proxy
                    })

                self.log.info('从全网代理官网更新代理成功: length = {}'.format(len(proxy_list)))
                return proxy_list
            except Exception as e:
                self.log.error('访问全网代理链接异常: ')
                self.log.exception(e)
                time.sleep(random.randint(1, 3))
        return []
